<!-- 弹窗 -->
<template>
  <div class="app-container">

    <!-- header -->
    <el-card>
      <div slot="header" class="header">
        <span>弹窗管理</span>
        <el-button type="success" icon="el-icon-plus" size="small" @click="onClickPopup('add')">添加弹窗</el-button>
      </div>

      <div style="marginTop:20px" class="filter-container">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="弹窗名称">
            <el-input v-model="searchData.name" clearable></el-input>
          </el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onClickPopup('search')">查询</el-button>
        </el-form>
      </div>
    </el-card>

    <!-- body -->
    <el-card style="marginTop:20px">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="#" min-width="80" />
        <el-table-column prop="name" label="标题" min-width="150" />
        <el-table-column prop="popupPage" label="出弹窗的页面" min-width="150">
          <template slot-scope="scope">
            {{scope.row.popupPage| popupPageFilter(editData.pageOptions)}}
          </template>
        </el-table-column>
        <el-table-column prop="jumpType" label="弹窗跳转页面" min-width="150">
          <template slot-scope="scope">
            {{scope.row.jumpType | jumpTypeFilter}}
          </template>
        </el-table-column>
        <el-table-column prop="jumpName" label="弹窗跳转内容" min-width="150">
        </el-table-column>
        <el-table-column prop="popupTimes" label="弹窗频率" min-width="150">
          <template slot-scope="scope">
            {{scope.row.popupTimes| popupTimesFilter}}
          </template>
        </el-table-column>
        <el-table-column prop="width" label="弹窗大小(高*宽)" min-width="150">
          <template slot-scope="scope">
            {{scope.row.height}}*{{scope.row.width}}
          </template>
        </el-table-column>
        <el-table-column prop="categoryPic" label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.pic" style="width:32px">
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isActive | activityTagFilter" effect="light" size="small">{{scope.row.isActive| activityStatusFilter}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.isActive" @click="onClickPopup('start',scope.row)" type="text">启动</el-button>
            <el-button v-if="scope.row.isActive" @click="onClickPopup('stop',scope.row)" type="text">暂停</el-button>
            <el-button @click="onClickPopup('edit',scope.row)" type="text">编辑</el-button>
            <el-button @click="onClickPopup('delete',scope.row)" type="text" class="red">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination background layout="prev, pager, next" @current-change="currentChange" :page-count="Math.ceil(this.pageInfo.total / this.pageInfo.pageSize)"></el-pagination>
      </div>
    </el-card>

    <!-- dialog -->
    <el-dialog :visible.sync="dialogFormVisible" :destroy-on-close="true" width="60%" :title="editData.isEdit?'编辑弹窗':'添加弹窗'" :before-close="onBeforeClose">
      <el-form ref="editForm" :rules="editRules" :model="editData">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="name" required>
          <el-input v-model="editData.name" placeholder="请输入弹窗名称" clearable style="width:50%" />
        </el-form-item>
        <el-form-item label="出弹窗的页面" :label-width="formLabelWidth" prop="popupPage" required>
          <el-select v-model="editData.popupPage" placeholder="请选择出弹窗的页面" clearable filterable style="width:50%">
            <el-option v-for="item in editData.pageOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="弹窗跳转页面" :label-width="formLabelWidth" prop="jumpType" required>
          <el-select v-model="editData.jumpType" placeholder="请选择弹窗跳转页面" filterable style="width:50%" @change="onChangeJumpType">
            <el-option v-for="item in editData.typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="弹窗跳转内容" :label-width="formLabelWidth" prop="jumpId" required>
          <!-- 商品 -->
          <el-select v-if="editData.jumpType==1" v-model="editData.jumpName" placeholder="请输入商品名称" clearable remote filterable style="width:50%" :remote-method="remoteMethodGoods" :loading="editData.selectLoading" @change="onChangeJumpId($event)">
            <el-option v-for="item in editData.selectSearchOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>

          <!-- 活动 -->
          <el-select v-else-if="editData.jumpType==2" v-model="editData.jumpName" placeholder="请输入活动名称" clearable remote filterable style="width:50%" :remote-method="remoteMethodActivity" :loading="editData.selectLoading" @change="onChangeJumpId($event)">
            <el-option v-for="item in editData.selectSearchOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="弹窗频率" :label-width="formLabelWidth" prop="popupTimes" required>
          <el-radio-group v-model="editData.popupTimes">
            <el-radio v-for="item in editData.popupTimesOptions" :key="item.value" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <span class="tb-tips">温馨建议：高宽比为3:2</span>
        <el-form-item label="弹窗高度" :label-width="formLabelWidth" prop="height" required>
          <el-input placeholder="请输入弹窗高度" v-model="editData.height" type="number" :min="1" style="width:50%" @change="onChangeSize('h')">
            <template slot="append">px</template>
          </el-input>
          <el-checkbox v-model="editData.lock">锁定高宽比</el-checkbox>
        </el-form-item>
        <el-form-item label="弹窗宽度" :label-width="formLabelWidth" prop="width" required>
          <el-input placeholder="请输入弹窗度" v-model="editData.width" type="number" :min="1" style="width:50%" @change="onChangeSize('w')">
            <template slot="append">px</template>
          </el-input>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth" prop="pic" required>
          <upload-image :defaultList='editData.picList' color="#1890ff" class="editor-upload-btn" :limit="1" @successCBK="syncImageList($event)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClickCancel">取 消</el-button>
        <el-button type="success" @click="onClickSave">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadImage from '@/components/UploadImage/UploadImage';
import config from './config';
export default {
  name: '',
  components: {
    UploadImage,
  },
  props: {},
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: '120px',
      pageInfo: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 展示数量
        total: 1, // 总记录数
      },
      searchData: {
        name: '',
        status: '',
      },
      tableData: [],
      editData: {
        isEdit: false,
        name: '',
        jumpType: 1,
        jumpId: '',
        jumpName: '',
        popupPage: null,
        popupTimes: 1,
        pic: '',
        width: 300,
        height: 450,

        picList: [],
        pageOptions: [],
        typeOptions: this.getJumpType(),
        popupTimesOptions: this.getPopupTimesOptions(),
        selectLoading: false, // 关联select loading
        selectSearchOptions: [], // 筛选列表的数据

        showJumpSearch: true,
      },
      editRules: {
        name: [{ required: true, message: '请输入弹窗标', trigger: 'blur' }],
        pic: [{ required: true, message: '请上传弹窗图片', trigger: 'blur' }],
        popupPage: [
          { required: true, message: '请选择出弹窗的页面', trigger: 'blur' },
        ],
        jumpType: [
          { required: true, message: '请选择弹窗跳转页面', trigger: 'blur' },
        ],
        jumpId: [
          {
            required: true,
            message: '请输入弹窗跳转内容',
            trigger: ['blur', 'change'],
          },
        ],
        popupTimes: [
          { required: true, message: '请选择弹窗频率', trigger: 'blur' },
        ],
      },
    };
  },
  created() {},
  mounted() {
    this.getPopupListPage();

    setTimeout(() => {
      this.getPopupPageList();
    }, 0);
  },
  filters: {
    // 出弹窗的页面
    popupPageFilter(popupPage, options) {
      const page = options.find((e) => e.id === popupPage);
      return page ? page.name : '';
    },
    // 弹窗跳转页面
    jumpTypeFilter(jumpType) {
      return config.jumpType[jumpType];
    },
    // 频率
    popupTimesFilter(popupTimes) {
      return config.popupTimes[popupTimes];
    },
    activityStatusFilter(status) {
      return config.status[status];
    },
    activityTagFilter(status) {
      return config.statusTag[status];
    },
  },
  computed: {},
  methods: {
    getJumpType() {
      return Object.getOwnPropertyNames(config.jumpType).map((value) => {
        return { label: config.jumpType[value], value: +value };
      });
    },

    getPopupTimesOptions() {
      return Object.getOwnPropertyNames(config.popupTimes).map((value) => {
        return { label: config.popupTimes[value], value: +value };
      });
    },

    onClickPopup(action, row) {
      switch (action) {
        case 'add':
          this.onClickAdd();
          break;
        case 'search':
          this.onClickSearch(row);
          break;
        case 'edit':
          this.onClickEdit(row);
          break;
        case 'delete':
          this.onClickDelete(row);
          break;

        case 'start':
          this.onClickActive(row, 1);
          break;
        case 'stop':
          this.onClickActive(row, 0);
          break;

        default:
          break;
      }
    },

    onClickAdd() {
      this.editData = {
        ...{},
        ...this.editData,
        ...{ isEdit: false },
      };
      this.dialogFormVisible = true;
    },

    onClickSearch() {
      this.pageInfo.pageNum = 1;
      this.getPopupListPage();
    },

    onClickEdit(row) {
      this.editData = {
        ...{},
        ...this.editData,
        ...{ isEdit: true },
        ...row,
        ...{ picList: [{ url: row.pic }] },
      };
      this.dialogFormVisible = true;
      // this.getActivityInfo(row);
      // this.getCategoryList();
    },

    onClickActive(row, active) {
      this.editData = {
        ...this.editData,
        ...row,
        ...{ isActive: active },
      };
      this.modifyPopup();
    },

    currentChange(val) {
      this.pageInfo.pageNum = val;
      this.getPopupListPage();
    },

    /** 窗体相关 */
    onBeforeClose(done) {
      this.editData = {
        ...this.editData,
        isEdit: false,
        name: '',
        jumpType: 1,
        jumpId: '',
        jumpName: '',
        popupPage: null,
        popupTimes: 1,
        pic: '',
        width: 375,
        height: 667,
        picList: [],
        selectSearchOptions: [],
      };
      done();
    },

    syncImageList(list) {
      this.editData.picList = list;
      this.editData.pic = list[0].url;
    },

    onChangeJumpType(e) {
      this.editData.jumpId = '';
      this.editData.jumpName = '';
    },

    onChangeJumpId(e) {
      if (e && e !== '') {
        const option = this.editData.selectSearchOptions.find(
          (item) => item.value === e
        );
        if (option) {
          this.editData.jumpName = option.label;
          this.editData.jumpId = option.value;
        }
      }
    },

    onChangeSize(action) {
      const standard = {
        height: 450,
        width: 300,
      };
      if (this.editData.lock) {
        switch (action) {
          case 'w':
            this.editData.height = Math.floor(
              (standard.height * this.editData.width) / standard.width
            );
            break;

          case 'h':
            this.editData.width = Math.floor(
              (standard.width * this.editData.height) / standard.height
            );
            break;

          default:
            break;
        }
      }
    },

    onClickCancel() {
      this.dialogFormVisible = false;
      this.$refs['editForm'].resetFields();
    },

    onClickSave() {
      this.$refs['editForm'].validate((valid) => {
        if (!valid) return;

        if (this.editData.isEdit) {
          this.modifyPopup();
        } else {
          this.addPopup();
        }
      });
    },
    async onClickDelete(row) {
      const confirm = await this.$confirm(
        `此操作将【永久删除】该弹窗, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {});

      confirm && this.deletePopup(row);
    },
    async getPopupListPage() {
      const params = {
        name: this.searchData.name,
      };
      const response = await this.$api.getPopupListPage(params);
      this.tableData = response.data;
      this.pageInfo.total = response.total;
    },

    async getPopupPageList() {
      const { data } = await this.$api.getPopupPageList();
      this.editData.pageOptions = data.map((e) => {
        return { id: e.id, name: e.name, path: e.path };
      });
    },

    async modifyPopup() {
      const {
        height,
        id,
        isActive,
        jumpId,
        jumpType,
        name,
        pic,
        popupPage,
        popupTimes,
        width,
      } = this.editData;
      const { success } = await this.$api.modifyPopup({
        height,
        id,
        isActive,
        jumpId,
        jumpType,
        name,
        pic,
        popupPage,
        popupTimes,
        width,
      });
      if (success) {
        this.$message.success('修改成功');
        this.dialogFormVisible = false;
        this.getPopupListPage();
      }
    },

    async addPopup() {
      const {
        height,
        isActive,
        jumpId,
        jumpType,
        name,
        pic,
        popupPage,
        popupTimes,
        width,
      } = this.editData;
      const { success } = await this.$api.addPopup({
        height,
        isActive,
        jumpId,
        jumpType,
        name,
        pic,
        popupPage,
        popupTimes,
        width,
      });
      if (success) {
        this.$message.success('修改成功');
        this.dialogFormVisible = false;
        this.getPopupListPage();
      }
    },

    async deletePopup({ id }) {
      const response = await this.$api.deletePopup({ id });
      if (response.success) {
        this.$message.success('删除成功');
        this.getPopupListPage();
      }
    },

    async remoteMethodActivity(keyword) {
      if (keyword === '') {
        this.editForm.selectSearchOptions = [];
        return;
      }
      this.editData.selectLoading = true;
      const { data, success, errMessage } = await this.$api
        .getActivityList({ name: keyword, status: 1 }) // 进行中
        .catch((err) => {
          this.$message({
            type: 'warning',
            message: `${err.errMessage}`,
          });
          this.editData.selectLoading = false;
          return;
        });
      if (!success) {
        this.$message({
          type: 'warning',
          message: `${errMessage || '系统繁忙，请稍后再试'}`,
        });
        this.editData.selectLoading = false;
        return;
      }

      if (data) {
        this.editData.selectSearchOptions = data.map((item) => {
          return {
            label: item.name,
            value: `${item.id}`,
          };
        });
      }
      this.editData.selectLoading = false;
    },

    async remoteMethodGoods(keyword) {
      if (keyword === '') {
        this.editForm.selectSearchOptions = [];
        return;
      }
      this.editData.selectLoading = true;
      const { data, success, errMessage } = await this.$api
        .getProductList({ productName: keyword }) // 进行中
        .catch((err) => {
          this.$message({
            type: 'warning',
            message: `${err.errMessage}`,
          });
          this.editData.selectLoading = false;
          return;
        });
      if (!success) {
        this.$message({
          type: 'warning',
          message: `${errMessage || '系统繁忙，请稍后再试'}`,
        });
        this.editData.selectLoading = false;
        return;
      }

      if (data) {
        this.editData.selectSearchOptions = data.map((item) => {
          return {
            label: item.productName,
            value: item.productId,
          };
        });
      }
      this.editData.selectLoading = false;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .tb-tips {
    height: 40px;
    line-height: 40px;
    margin-left: 120px;
    color: red;
  }
}
::v-deep {
  .el-dialog {
    margin-top: 12vh !important;
  }
  .el-dialog__body {
    padding-bottom: 0;
  }
  .el-dialog__footer {
    padding: 10px 20px;
  }
  .el-checkbox {
    margin-left: 20px;
  }
}
</style>
